import { Table, Icon, Row, Col, Button, Spin, Radio, Modal, message, Select } from 'antd';
import { WeaTools, WeaInput, WeaSelect, WeaBrowser, WeaTextarea, WeaCheckbox, WeaDatePicker, WeaTimePicker, WeaInputNumber, WeaError } from 'ecCom';
import './style/index.css';
import equal from 'deep-equal';
import { toJS } from 'mobx';

const Option = Select.Option;
import { WeaLocaleProvider } from 'ecCom';
import { isEmail, isURL } from '../../../util/index';

const getLabel = WeaLocaleProvider.getLabel;

class WeaTableEdit extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showGroup: props.showGroup ? props.showGroup : false,
      datasEdit: [],
    };
    this.doAdd = this.doAdd.bind(this);
    this.doUpdate = this.doUpdate.bind(this);
    this.doSave = this.doSave.bind(this);
    this.doDelete = this.doDelete.bind(this);

    this.isBrowser = new Array();
    this.isCheckbox = new Array();
    this.isDatePicker = new Array();
    this.isTimePicker = new Array();
    this.isInput1 = new Array();
    this.isInput2 = new Array();
    this.isSelect = new Array();
    this.isTextarea = new Array();
  }

  componentDidMount() {

  }

  render() {
    const { showGroup } = this.state;
    const { title, needAdd, needCopy, columns, datas, parentStore } = this.props;
    let columnsTemp = columns;
    if (!needAdd) {
      const columnsRead = JSON.parse(JSON.stringify(columns)); // deep copy
      for (const ci of columnsRead) {
        ci.viewAttr = 1;
        ci.com[0].viewAttr = 1;
      }
      columnsTemp = columnsRead;
    }

    return (
      <div className="wea-crm-table-edit" >
        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@nb8v15`} className="wea-title">
          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@w21uje`} span="20">
            <div>{title}</div>
          </Col>
          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@wnrorl`} span="4" style={{ textAlign: 'right', paddingRight: 10 }} className="wea-content">
            {needAdd && <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@cvv1pl`} type="primary" title={getLabel(1421, '新增')} size="small" onClick={this.doAdd}><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@if1tzu`} type="plus" /></Button>}
            <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@4u7z9i`} type={showGroup ? 'up' : 'down'} onClick={() => this.setState({ showGroup: !showGroup })} />
          </Col>
        </Row>
        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@rix8a2`} className="wea-content" style={{ display: showGroup ? 'block' : 'none' }}>
          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@71x891`} span={24}>
            <Table
              ecId={`${this && this.props && this.props.ecId || ''}_Table@h6a1v5`}
              rowKey={'id'}
              columns={this.reDefineColumns(toJS(columnsTemp))}
              dataSource={datas}
              pagination={false}
              className="contracter-edit-table"
              scroll={{ x: columns.length * 80 }}
            />
          </Col>
        </Row>
      </div>
    );
  }

  reDefineColumns(columns) {
    const { showGroup } = this.state;
    if (showGroup) {
      columns.map((col) => {
        col.render = (text, record, index) => this.getColRender(col, text, record, index);
        return col;
      });
    }
    return columns;
  }

  getColRender(col, text, record, index) {
    const { title, com, hasIcon = false, hasadd = false } = col;
    const notNew = record.notNew;
    const c = com[0];
    const coms = [];
    let newCom;
    const { domkey, viewAttr = 2, formItemType = 'INPUT', subType, otherParams, options = [], browserConditionParam = {}, width } = c;

    const fieldName = domkey[0];
    const fieldValue = record[fieldName];

    const fieldHtmlType = formItemType.toUpperCase();
    if (fieldHtmlType === 'INPUT') {
      const newWidth = width;
      let viewAddContactBtn = false;
      let viewQQIcon = false;
      const needAddContact = this.props.needAddContact;
      if (hasadd && notNew && needAddContact) {
        // newWidth = "75%";
        viewAddContactBtn = true;
      }
      if (hasIcon && notNew) {
        // newWidth = "75%";
        viewQQIcon = true;
      }
      if (fieldName == 'imcode') {
        // newWidth = "80px";
      }

      newCom = (<div style={{ maxWidth: '120px', minWidth: '90px' }}>
        {subType == '1' &&
        <WeaError
          ecId={`${this && this.props && this.props.ecId || ''}_WeaError@7o4j11`}
          tipPosition="top"
          ref={(obj) => {
					    this.isInput1.push(obj);
					  }}
          style={{ width: '100%' }}
          error={`"${title}"${getLabel(21423, '未填写')}`}
        >
          <WeaInput
            ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@1k0siw`}
            defaultValue={fieldValue}
            value={fieldValue}
            style={{ width: '100%', display: 'inline-block' }}
            onChange={(value) => {
					      this.props.parentStore.synContacterData(index, fieldName, value);
					    }}
            onBlur={(value) => {
					      if (notNew) {
					        if (value == '' && viewAttr == 3) {
					          this.showErrors();
					        } else {
					          this.doUpdate(record, index, fieldName, value);
					        }
					      }
					    }}
            viewAttr={viewAttr}
            title={`${title}:${fieldValue}`}
          />
        </WeaError>
        }
        {(subType == '2' || subType == '3') &&
        <WeaError
          ecId={`${this && this.props && this.props.ecId || ''}_WeaError@wqnpyj`}
          tipPosition="top"
          ref={(obj) => {
					    this.isInput2.push(obj);
					  }}
          style={{ width: '100%' }}
          error={`"${title}"${getLabel(21423, '未填写')}`}
        >
          <WeaInput
            ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@bzwhhm`}
            inputType={'form'}
            detailtype={subType}
            format={{}}
            qfws={subType == '3' ? otherParams.qfws : 0}
            defaultValue={fieldValue}
            value={fieldValue}
            style={{ width: '100%', display: 'inline-block' }}
            onChange={(value) => {
					      this.props.parentStore.synContacterData(index, fieldName, value);
					    }}
            onBlur={(value) => {
					      if (notNew) {
					        if (value == '' && viewAttr == 3) {
					          this.showErrors();
					        } else {
					          this.doUpdate(record, index, fieldName, value);
					        }
					      }
					    }}
            viewAttr={viewAttr}
            title={`${title}:${fieldValue}`}
          />
        </WeaError>
        }
        {
          viewAddContactBtn && <a onClick={() => this.props.showRightContactlog(false, record)} title={getLabel(611, '添加') + getLabel(17532, '联系记录')} style={{ marginLeft: '5px' }}><i className="icon-crm-wenjiantianjia" /></a>
        }
        {
          viewQQIcon && <div className="icon-crm-qq-a"><a href={`${`tencent://message/?uin=${record[domkey[0]]}&Site=&Menu=yes`}`} title={getLabel(84273, '点击发起QQ会话')}><i className="icon-crm-qq" /></a></div>
        }
      </div>);
    } else if (fieldHtmlType === 'TEXTAREA') {
      newCom = (<div style={{ maxWidth: '180px', minWidth: '100px' }}>
        <WeaError
          ecId={`${this && this.props && this.props.ecId || ''}_WeaError@vgepk0`}
          tipPosition="top"
          ref={(obj) => {
            this.isTextarea.push(obj);
          }}
          style={{ width: '100%' }}
          error={`"${title}"${getLabel(21423, '未填写')}`}
        >
          <WeaTextarea
            ecId={`${this && this.props && this.props.ecId || ''}_WeaTextarea@qepu0y`}
            style={{ width: '100%' }}
            value={fieldValue}
            viewAttr={viewAttr}
            onChange={(value) => {
              this.props.parentStore.synContacterData(index, fieldName, value);
            }}
            onBlur={(value) => {
              if (notNew) {
                if (value == '' && viewAttr == 3) {
                  this.showErrors();
                } else {
                  this.doUpdate(record, index, fieldName, value);
                }
              }
            }}
          /></WeaError>
      </div>);
    } else if (fieldHtmlType === 'BROWSER') {
      if (subType == '2') {
        newCom = (<div style={{ maxWidth: '100px', minWidth: '100px' }}>
          <WeaError
            ecId={`${this && this.props && this.props.ecId || ''}_WeaError@twvb35`}
            tipPosition="top"
            ref={(obj) => {
              this.isDatePicker.push(obj);
            }}
            style={{ width: '100%' }}
            error={`"${title}"${getLabel(21423, '未填写')}`}
          >
            <WeaDatePicker
              ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@2uh9e7`}
              value={fieldValue}
              style={{ width: '100%' }}
              viewAttr={viewAttr}
              onChange={(value) => {
                if (notNew) {
                  if (value == '' && viewAttr == 3) {
                    this.showErrors();
                  } else {
                    this.doUpdate(record, index, fieldName, value);
                  }
                }
                this.props.parentStore.synContacterData(index, fieldName, value);
              }}
            /> </WeaError>
        </div>);
      } else if (subType == '19') {
        newCom = (<div style={{ maxWidth: '100px', minWidth: '100px' }}>
          <WeaError
            ecId={`${this && this.props && this.props.ecId || ''}_WeaError@kl70zm`}
            tipPosition="top"
            ref={(obj) => {
              this.isTimePicker.push(obj);
            }}
            style={{ width: '100%' }}
            error={`"${title}"${getLabel(21423, '未填写')}`}
          >
            <WeaTimePicker
              ecId={`${this && this.props && this.props.ecId || ''}_WeaTimePicker@vygatg`}
              value={fieldValue}
              style={{ width: '100px' }}
              viewAttr={viewAttr}
              onChange={(value) => {
                this.props.parentStore.synContacterData(index, fieldName, value);
                setTimeout(() => {
                  if (notNew) {
                    if (value == '' && viewAttr == 3) {
                      this.showErrors();
                    } else {
                      this.doUpdate(record, index, fieldName, value);
                    }
                  }
                }, 200);
              }}
            />
          </WeaError>
        </div>);
      } else {
        newCom = (<div style={{ maxWidth: '120px', minWidth: '100px' }}>
          <WeaError
            ecId={`${this && this.props && this.props.ecId || ''}_WeaError@tlotui`}
            tipPosition="top"
            ref={(obj) => {
              this.isBrowser.push(obj);
            }}
            style={{ width: '100%' }}
            error={`"${title}"${getLabel(21423, '未填写')}`}
          >
            <WeaBrowser
              ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@cfobo9`}
              layout={document.body}
              {...browserConditionParam}
              replaceDatas={toJS(record[`${fieldName}ReplaceDatas`])}
              style={{ width: '100%' }}
              viewAttr={viewAttr}
              onChange={(ids, names, bDatas) => {
                if (notNew) {
                  if (ids == '' && viewAttr == 3) {
                    this.showErrors();
                  } else {
                    this.doUpdate(record, index, fieldName, ids);
                  }
                }
                this.props.parentStore.synContacterData(index, fieldName, ids);
                this.props.parentStore.contacterInfo.columnsData[index][`${fieldName}ReplaceDatas`] = bDatas;
              }}
            /> </WeaError>
        </div>);
      }
    } else if (fieldHtmlType === 'SELECT') {
      newCom = (<div style={{ maxWidth: '100px', minWidth: '100px' }}>
        <WeaError
          ecId={`${this && this.props && this.props.ecId || ''}_WeaError@u2edbd`}
          tipPosition="top"
          ref={(obj) => {
            this.isSelect.push(obj);
          }}
          style={{ width: '100%' }}
          error={`"${title}"${getLabel(21423, '未填写')}`}
        >
          <WeaSelect
            ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@r7j95u`}
            defaultValue={fieldValue}
            value={fieldValue}
            options={options}
            viewAttr={viewAttr}
            style={{ width: '100px' }}
            onChange={(value) => {
              if (notNew) {
                this.doUpdate(record, index, fieldName, value);
              }
              this.props.parentStore.synContacterData(index, fieldName, value);
            }}
          />
        </WeaError>
      </div>);
    } else if (fieldHtmlType === 'CHECKBOX') {
      newCom = (<div style={{ maxWidth: '50px', minWidth: '50px' }}>
        <WeaCheckbox
          ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@dcs3h2`}
          style={{ width: '100%' }}
          value={fieldValue}
          onChange={(value) => {
            if (notNew) {
              this.doUpdate(record, index, fieldName, value);
            }
            this.props.parentStore.synContacterData(index, fieldName, value);
          }}
        />
      </div>);
    } else if (fieldHtmlType === 'RADIO') {
      newCom = (<div style={{ maxWidth: '50px', minWidth: '50px' }}>
        <Radio
          ecId={`${this && this.props && this.props.ecId || ''}_Radio@1io1di`}
          style={{ width: '50px' }}
          onClick={() => {
            if (notNew) {
              this.doUpdate(record, index, fieldName, 1);
            }
            this.props.parentStore.resetMainContacter(record);
          }}
          checked={fieldValue == 1}
          disabled={viewAttr == 1}
        />
      </div>);
    } else if (fieldHtmlType === 'OPERATION') {
      if (notNew) {
        newCom = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@btabq4`} type="primary" title={getLabel(17463, '明细')} size="small" onClick={() => openFullWindowHaveBarForCrm(`/main/crm/contacterView?contacterId=${record.contacterid}`)}><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@292dnh`} type="file-text" /></Button>;
      } else {
        newCom = (<div style={{ minWidth: '30px' }}>
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@iit3qe`} id="cetSave" type="primary" title={getLabel(86, '保存')} size="small" onClick={() => { this.doSave(); }}><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@7fxv3r`} type="save" /></Button>
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@jl6j0k`} id="cetDel" type="primary" title={getLabel(91, '删除')} size="small" onClick={() => { this.doDelete(); }}><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@i5h3mu`} type="minus" /></Button>
        </div>);
      }
    }
    coms.push(newCom);
    return <div>{coms}</div>;
  }

  doAdd() {
    const { columns, datas, canAdd } = this.props;
    if (canAdd) {
      const _datas = datas.map(d => ({ ...d }));
      const _data = {};
      for (const c of columns) {
        if (c.dataIndex) {
          _data[c.dataIndex] = '';
        }
      }
      _data.notNew = false;
      _datas.push(_data);
      typeof this.props.onChange === 'function' && this.props.onChange(_datas);
      typeof this.props.onAddChange === 'function' && this.props.onAddChange();
    }
  }

  doUpdate(record, index, key, value, viewAttr) {
    let errorCase = 0;
    if (record) {
      if (('contacteremail' in record) && record.contacteremail != '' && !isEmail(record.contacteremail)) {
        errorCase = 1;
      }
      switch (errorCase) {
        // 邮件格式判断
        case 1:
				 message.error(getLabel(71, '邮件') + getLabel(15196, '格式') + getLabel(127353, '错误'));

				 break;
          // 可添加别的格式判断
        default:
          if (record.contacterid && this.showErrors()) {
            typeof this.props.onEditChange === 'function' && this.props.onEditChange(record, index, key, value);
          }
      }
    }
  }

  doSave() {
    typeof this.props.onSave === 'function' && this.props.onSave();
  }

  doDelete() {
    typeof this.props.onDelete === 'function' && this.props.onDelete();
  }
  showErrors() {
    let boole = true;
    toJS(this.isInput1).map((c) => {
      if (c && !c.props.children.props.value && c.props.children.props.viewAttr == '3') {
        c.showError();
        boole = false;
      }
    });
    toJS(this.isInput2).map((c) => {
      if (c && !c.props.children.props.value && c.props.children.props.viewAttr == '3') {
        c.showError();
        boole = false;
      }
    });
    toJS(this.isBrowser).map((c) => {
      if (c && (!c.props || !c.props.children[0].props.replaceDatas || !c.props.children[0].props.replaceDatas[0]) && c.props.children[0].props.viewAttr == 3) {
        c.showError();
        boole = false;
      }
    });
    // toJS(this.isCheckbox).map(c => {//check框验证，先不写了
    // if(c&&c.props.children.props.value==0&&c.props.children.props.viewAttr=="3"){
    // 	c.showError();
    // 	boole =false;
    // 	}
    // });
    toJS(this.isDatePicker).map((c) => {
      if (c && !c.props.children[0].props.value && c.props.children[0].props.viewAttr == '3') {
        c.showError();
        boole = false;
      }
    });
    toJS(this.isTimePicker).map((c) => {
      if (c) {
        if (c.props.children.props.value == '' && c.props.children.props.viewAttr == '3') {
          c.showError();
          boole = false;
        }
      }
    });
    toJS(this.isSelect).map((c) => {
      if (c && !c.props.children.props.value && c.props.children.props.viewAttr == '3') {
        c.showError();
        boole = false;
      }
    });
    toJS(this.isTextarea).map((c) => {
      if (c && !c.props.children.props.value && c.props.children.props.viewAttr == '3') {
        c.showError();
        boole = false;
      }
    });
    return boole;
  }
}

export default WeaTableEdit;
